package cz.muni.fi.pa165.musiclibrary.musiclibraryweb.components;

import org.apache.commons.lang3.StringUtils;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.ImageButton;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.request.resource.PackageResourceReference;
import org.apache.wicket.request.resource.ResourceReference;

import cz.muni.fi.pa165.musiclibrary.musiclibraryweb.images.ImageAnchor;
import cz.muni.fi.pa165.musiclibrary.musiclibraryweb.pages.search.result.SearchResultPage;

/**
 *
 * @author Maros Kucbel
 * @date 2012-11-24T22:10:53+0100
 */
public final class SearchForm extends Form<SearchModel> {

    public SearchForm(String id) {
        this(id, Model.of(new SearchModel()));
    }
    
    public SearchForm(String id, SearchModel model) {
        this(id, Model.of(model));
    }
    
    public SearchForm(String id, IModel<SearchModel> model) {
        super(id, model);
    }

    @Override
    protected void onInitialize() {
        super.onInitialize();
        this.initComponents();
    }
    
    private void initComponents() {
        IModel<String> searchFieldModel = new PropertyModel<String>(this.getModelObject(), "searchString");
        TextField<String> searchField = new TextField<String>(ComponentIDs.SEARCH_FIELD, searchFieldModel);
        this.add(searchField);
        ResourceReference searchIcon = new PackageResourceReference(ImageAnchor.class, "search_icon_16px.png");
        ImageButton searchButton = new ImageButton(ComponentIDs.SEARCH_BUTTON, searchIcon);
        this.add(searchButton);
    }

    @Override
    protected void onSubmit() {
        SearchModel model = this.getModelObject();
        if (StringUtils.isNotBlank(model.getSearchString())) {
            PageParameters pageParameters = new PageParameters();
            pageParameters.add("s", model.getSearchString());
            this.setResponsePage(SearchResultPage.class, pageParameters);
        }
    }
    
    /** Identifiers of added components. */
    private static final class ComponentIDs {
        /** Search field. */
        private static final String SEARCH_FIELD = "searchField";
        /** Search button. */
        private static final String SEARCH_BUTTON = "searchButton";
    }
}